<?php

namespace App\Http\Controllers\Admin\Api;


use App\Exceptions\LogicException;
use App\Http\Controllers\Controller;
use App\Models\Api\Apis;
use App\Models\Api\ApisParam;
use App\Models\Api\ApisValidator;
use App\Models\Api\SampleValue;
use App\Utils\QueryUtil;
use App\Utils\ResUtil;
use App\Models\Adminer\Admins;
use App\Services\RunTestService;
use App\Services\makeReportService;



class ApisParamController extends Controller
{
    public function list()
    {
        $request = request()->all();
        $query = ApisParam::where(function($query) use($request) {
            QueryUtil::selectBuild($query, $request, [
                ['api_id', '='],
                ['param', 'like', 'param'],
                ['created_adminer', 'like', 'created_adminer'],
                ['updated_adminer', 'like', 'updated_adminer'],
                ['id', '=']
            ]);
        });

        $total = $query->count();
        $models = QueryUtil::queryListParams($query);
        $list = [];
        foreach($models as $i => $v) {
            $list[$i] = $v?->label()?->toArray();
        }
        $hasMore = QueryUtil::hasMore(sizeof($list));
        return $this->ok(compact('list', 'total', 'hasMore'));
    }

    public function edit()
    {
        $data = request()->only([
            'id', 'api_id', 'param'
        ]);
        $rule = [
            'id' => '',
            'api_id' => 'required',
            'param' => 'required',
        ];
        $validator = validatorService()->checkValidator($rule, $data, ApisParam::$fillables);
        if ($validator['code'] != 200) {
            throw new LogicException($validator['data']);
        }

//        $is_json = function($string) {
//            json_decode($string);
//            return (json_last_error() == JSON_ERROR_NONE);
//        };
//
//        if(!$is_json($data['param'])) {
//            throw new LogicException('请填写正确的json格式参数');
//        }

        if($data['id'] ?? '') {
            $ApisParam = ApisParam::find($data['id']);
            if(!$ApisParam) {
                throw new LogicException(ResUtil::NOT_DATA);
            }
        } else {
            $ApisParam = new ApisParam;
            $ApisParam->created_adminer = Admins::getInfoById($this->authAdmin()->id);
        }

        $api = Apis::find($data['api_id']);
        if(!$api) {
            throw new LogicException('接口不存在');
        }

        $ApisParam->fill([
            'api_id' => $api->id,
            'param' =>  $data['param'],
            'updated_adminer' => Admins::getInfoById($this->authAdmin()->id),
        ]);
        $ApisParam->save();
        return $this->ok();
    }

    public function enable()
    {
        $data = request()->all();
        $rule = [
            'id' => 'integer|required',
        ];
        $validator = validatorService()->checkValidator($rule, $data, ApisParam::$fillables);
        if ($validator['code'] != 200) {
            throw new LogicException($validator['data']);
        }
        $ApisParam = ApisParam::find($data['id']);
        if(!$ApisParam) {
            throw new LogicException(ResUtil::NOT_DATA);
        }

        SampleValue::where('param_id', $ApisParam->id)->delete();
        ApisValidator::where('param_id', $ApisParam->id)->delete();
        $ApisParam->delete();
        return $this->ok();
    }

    public function viewRes(RunTestService $runTestService, makeReportService $makeReportService)
    {
        $data = request()->all();
        $rule = [
            'id' => 'integer|required',
        ];
        $validator = validatorService()->checkValidator($rule, $data, ApisParam::$fillables);
        if ($validator['code'] != 200) {
            throw new LogicException($validator['data']);
        }

        $param = ApisParam::find($data['id']);
        if(!$param) {
            throw new LogicException('用例不存在');
        }

        $api = Apis::find($param->api_id);
        if(!$api) {
            throw new LogicException('接口不存在');

        }

        $api_info = $makeReportService->getUrl($api->api);
        $url = $api_info['scheme']."://".$api_info['domain'].$api_info['path'];
        if(!empty($api_info['port'])) {
            $url = $api_info['scheme']."://".$api_info['domain'] .':'.$api_info['port'].$api_info['path'];
        }
        $param1 = json_decode(json_encode($param->param), true);
        $headers1  = Apis::getHeaders($api) ?: [];
        $params = $runTestService->getSampleValue($param1);
        $headers =  $runTestService->getSampleValue($headers1);
        $method = Apis::$method_type_maps[$api->method_type] ?? "POST";
        $res = $runTestService->initServe()->curlRun($url, $params, $headers, $method);

        // 取样器
        $sampleValues =  SampleValue::getBYParamID($param->id);
        if(empty($sampleValues?->toArray())) {
            return $this->ok($res);
        }
        $biao1 = false;
        foreach($sampleValues as $sampleValue) {
            $param_res = $res['res_body']; // array
            $sample_rule = $sampleValue->sample_rule; // $.data.list.0.id
            $arr_rule = explode('.', $sample_rule);

            foreach ($arr_rule as $rule) {
                if ($rule == '$') {
                    continue;
                }
                if(!isset($param_res[$rule])) {
                    //  // 0未取样 1取样成功 2取样失败
                    $sampleValue->status = SampleValue::STATUS_FAIL;
                    $sampleValue->save();
                    $biao1 = true;
                    break;
                }
                $param_res = $param_res[$rule];
            }

            if ($biao1) {
                $biao1 = false;
                continue;
            }
            $sampleValue->status = SampleValue::STATUS_SUCCESS;
            $sampleValue->sample_value = $param_res;
            $sampleValue->save();
        }

        return $this->ok($res);
    }
}
